<!--
 * @Description: 附件预览
 
  -- 组件调用
  <tw-upload-preview ref="upFilePreview"></tw-upload-preview>

 * @Author: DHL
 * @Date: 2020-04-28 15:52:56
 * @LastEditors: DHL
 * @LastEditTime: 2021-01-12 15:36:34
 -->
<template>
  <div class="upload-preview-wrapper">
    <div class="image-container">
      <template v-for="(item, index) in fileList">
        <el-image
          :src="`${item.url}?width=200`"
          :zoom-rate="1.2"
          :max-scale="7"
          :min-scale="0.2"
          :preview-src-list="previewSrcList"
          :initial-index="index"
          fit="cover"
        />
      </template>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { apiFileSearch } from '@/api/common/fileCenter'
  import { arraySerialize } from '@/utils/arrayUtils'
  import { isEmpty, isNotEmpty } from '@/utils/isUtils'
  import { log } from '@/utils/logUtils'

  const env = import.meta.env

  const { VITE_APP_BASE_FILES } = env

  //////////////////////////////////////////////////
  // 属性
  //////////////////////////////////////////////////

  interface Props {
    /**
     * 业务主键
     */
    bizId?: string

    /**
     * 业务类型
     */
    bizType?: string

    /**
     * 附件ID集合
     */
    fileIds?: string
  }

  const props = withDefaults(defineProps<Props>(), {
    bizId: '',
    bizType: '',
    fileIds: ''
  })

  /**
   * 文件集合
   */
  const fileList = ref([] as Array<any>)

  watch(
    () => props,
    () => {
      loadData()
    },
    {
      deep: true,
      immediate: true
    }
  )

  /**
   * 图片预览集合
   */
  const previewSrcList = computed(() => {
    return arraySerialize(fileList.value, 'url') as Array<string>
  })

  //////////////////////////////////////////////////
  // 函数
  //////////////////////////////////////////////////

  /**
   * 回显文件
   * params: { fileIds: '', bizId: '', bizType: '' }
   */
  function loadData() {
    if (isEmpty(props.fileIds) && isEmpty(props.bizId)) {
      return
    }

    apiFileSearch(props).then((result) => {
      if (result?.success) {
        fileList.value = []

        result.data.forEach((item) => {
          if (item && item.fileType.indexOf('image') > -1) {
            if (isNotEmpty(VITE_APP_BASE_FILES)) {
              let thumbnailUrl = item.thumbnailBasePath
              if (isEmpty(thumbnailUrl)) {
                thumbnailUrl = `${item.basePath}`
              }
              thumbnailUrl = `${VITE_APP_BASE_FILES}${thumbnailUrl}`
              item.url = thumbnailUrl
            } else {
              item.url = `${item.filePath}`
            }

            fileList.value.push(item)
          }
        })
      } else {
        log.warn(result?.message || '')
      }
    })
  }
</script>

<style lang="scss" scoped>
  .upload-preview-wrapper {
    .image-container {
      .el-image {
        width: 100px;
        height: 100px;
        margin-right: 10px;
      }
    }
  }
</style>
